package com.cloud.filter;

import com.cloud.common.R;
import com.cloud.feignclient.UserFeignClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/7/7 14:52
 * @Desc
 * @Remarks
 */
@PropertySource("classpath:loginFilter.properties")
@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    @Value("#{'${extends.urls}'.split(',')}")
    List<String> urls;

    @Autowired
    UserFeignClient userFeignClient;

    public static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (null != urls && urls.contains(request.getURI().getPath())) {
            return chain.filter(exchange);
        }
        String access_token = request.getHeaders().getFirst("access_token");
        if (!StringUtils.hasLength(access_token)) {
            return onError(exchange, "尚未登录");
        }
        R<String> r = userFeignClient.validToken(access_token);
        if (r.getCode() == 200) {
            ServerHttpRequest shr = request.mutate().header("uid", r.getData()).build();
            return chain.filter(exchange.mutate().request(shr).build());
        }
        return onError(exchange, r.getMsg());
    }

    public Mono<Void> onError(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json");

        R result = new R.Builder<>().buildCustomize(HttpStatus.UNAUTHORIZED.value(), msg);
        String s = "";
        try {
            s = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } finally {
        }
        DataBuffer wrap = response.bufferFactory().wrap(s.getBytes());
        return response.writeWith(Flux.just(wrap));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
